# -*- coding;utf-8 -*-
"""
File name : models.PY
Program IDE : PyCharm
Create file time: 2022/3/2 15:02
File Create By Author : 朱清闯
"""

from account.models import User, ClassGrade
from utils.fields import OrderField
from django.utils import timezone
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

SUBJECT_TYPE_CHOICE = (
    (1, '信息技术'),
    (2, '通用技术'),
    (3, '职高计算机')
)


class Subject(models.Model):
    """
    课程类别
    """
    name = models.CharField(max_length=11, verbose_name='学科名')
    order = models.IntegerField(blank=True, verbose_name='排序序号', default=0)

    class Meta:
        verbose_name = '学科'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Course(models.Model):
    """
    课程类别
    """
    Coures_Type = (
        ('必修1', '必修1'),
        ('必修2', '必修2'),
        ('选必修1', "选必修1")
    )
    subject = models.ForeignKey(to='Subject', on_delete=models.CASCADE, blank=False, related_name='courses', default=1)
    name = models.CharField(max_length=11, verbose_name='课程名')
    overview = models.CharField(max_length=10, verbose_name='小标题', choices=Coures_Type, default=Coures_Type[0][0])
    intro = models.CharField(max_length=100, verbose_name='课程简介')
    order = models.IntegerField(blank=True, verbose_name='排序序号', default=0)

    class Meta:
        verbose_name = '课程'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Chapter(models.Model):
    name = models.CharField(max_length=20, verbose_name='章名')
    overview = models.CharField(max_length=20, verbose_name='简称',
                                help_text='显示侧边，比如算法的概念与描述，简写为概念与描述',
                                blank=True)
    course = models.ForeignKey(to='Course', on_delete=models.CASCADE, blank=False, related_name='chapters')
    order = OrderField(blank=True, for_fields=['course'], verbose_name='排序序号',
                       help_text="决定同个课程内的各节之间的排序序号，升序排序比如第一章为1,第二章为2；1.1为1；1.3为了3")

    class Meta:
        verbose_name = '章'
        verbose_name_plural = verbose_name
        ordering = ["course", 'order']

    def __str__(self):
        return self.name


class IsXimuManager(models.Manager):
    def get_queryset(self):
        return super(IsXimuManager, self).get_queryset().filter(ximu=True)


class IsNotXimuManager(models.Manager):
    def get_queryset(self):
        return super(IsNotXimuManager, self).get_queryset().filter(ximu=False)


class Section(models.Model):
    name = models.CharField(max_length=20, verbose_name='节名')
    overview = models.CharField(max_length=20, verbose_name='简称', help_text='5个字以内，用于微信小程序显示侧边，比如算法的概念与描述，简写为概念与描述',
                                blank=True)
    chapter = models.ForeignKey(to='Chapter', on_delete=models.CASCADE, blank=False, related_name='sections')
    order = OrderField(blank=True, for_fields=['chapter'], verbose_name='排序序号',
                       help_text="决定同一章内的各节之间的排序序号，升序排序比如第一章为1,第二章为2；1.1为1；1.3为了3")
    ximu = models.BooleanField(verbose_name='是否细目表', default=False)
    objects = models.Manager()
    IsXimu = IsXimuManager()
    IsNotXimu = IsNotXimuManager()

    class Meta:
        verbose_name = '节'
        verbose_name_plural = verbose_name
        ordering = ["chapter", 'order']

    def __str__(self):
        return self.name


class KnowledgePoint(models.Model):
    name = models.CharField(max_length=20, verbose_name='名称')
    overview = models.CharField(max_length=20, verbose_name='简称', help_text='5个字以内，用于微信小程序显示侧边，比如算法的概念与描述，简写为概念与描述',
                                blank=True)
    content = models.CharField(max_length=500, verbose_name='知识点内容', blank=True)
    owner = models.ForeignKey(User, verbose_name='录入者', on_delete=models.CASCADE, related_name="knowledgepoints")
    section = models.ForeignKey(Section, on_delete=models.CASCADE, blank=False, related_name='knowledgepoints')
    order = OrderField(blank=True, for_fields=['section'], verbose_name='排序序号',
                       help_text="决定各节之间的排序序号，升序排序比如第一章为1,第二章为2；1.1为1；1.3为了3")
    subject = models.ForeignKey(to='Subject', on_delete=models.CASCADE, blank=False, default=1,
                                related_name='knowledgepoints')
    ximu = models.BooleanField(verbose_name='是否细目表知识点', default=False)
    objects = models.Manager()
    IsXimu = IsXimuManager()
    IsNotXimu = IsNotXimuManager()
    question = models.ManyToManyField('Questions', through='KnowledgePoint2Question',
                                      through_fields=('knowledgepoint', 'question'))

    class Meta:
        verbose_name = '知识点'
        verbose_name_plural = verbose_name
        ordering = ['section', 'order']

    def __str__(self):
        return self.name


class OnlineManager(models.Manager):
    def get_queryset(self):
        return super(OnlineManager, self).get_queryset().filter(online=True)


class PublicManager(models.Manager):
    def get_queryset(self):
        return super(PublicManager, self).get_queryset().filter(open_level='public')


class PublicAndOnlineManager(models.Manager):
    def get_queryset(self):
        return super(PublicAndOnlineManager, self).get_queryset().filter(open_level='public').filter(online=True)


OPEN_LEVEL_CHOICES = (
    ("public", "所有人可见"),
    ("private", "仅自己可见"),
    ("friend", "好友可见")
)
QUESTION_TYPE_CHOICES = (
    (0, '简答题'),
    (1, '选择题'),
    (2, '填空题'),
    (3, '多选题'),
    (4, '判断题'),
)
DIFFICULTY_LEVEL_CHOICES = (
    (0, '送分'),
    (1, '入门'),
    (2, '容易'),
    (3, '较难'),
    (4, '很难'),
    (5, '压轴')
)


class Questions(models.Model):
    content = models.TextField(verbose_name='内容', blank=False)
    answer = models.TextField(verbose_name='正确答案', blank=False, default='略')
    explain = models.TextField(verbose_name='解析', blank=False, default='略')
    reference = models.CharField(max_length=100, verbose_name='引用哪里', blank=True, default='原创')
    type = models.SmallIntegerField(verbose_name='题型', choices=QUESTION_TYPE_CHOICES, default=1)
    difficulty_level = models.SmallIntegerField(verbose_name='难度', choices=DIFFICULTY_LEVEL_CHOICES, default=2)
    owner = models.ForeignKey(User, verbose_name='录入者', on_delete=models.CASCADE, related_name="questions")
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='录入时间')
    publish_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    last_edit_time = models.DateTimeField(auto_now_add=True, verbose_name='修改时间')
    open_level = models.CharField(verbose_name='开放程度', choices=OPEN_LEVEL_CHOICES, max_length=10,
                                  default=OPEN_LEVEL_CHOICES[0][0])
    top = models.BooleanField(default=False, verbose_name='置顶')
    # knowledgepoint = models.ForeignKey(to='KnowledgePoint', on_delete=models.CASCADE, verbose_name='知识点',
    #                                    related_name="questions")
    order = OrderField(blank=True, for_fields=['knowledgepoint'], verbose_name='排序序号',
                       help_text="数字小的靠前")
    pictures = models.TextField(verbose_name='题干插图', default='', blank=True)
    pictures_answer = models.TextField(verbose_name='答案插图', default='', blank=True)
    pictures_explain = models.TextField(verbose_name='答案插图', default='', blank=True)
    pictures_scale = models.TextField(verbose_name='宽与高的像素，两者用@分隔，每组用-分隔', default='', blank=True)
    pictures_answer_scale = models.TextField(verbose_name='宽与高的像素，两者用@分隔，每组用-分隔', default='', blank=True)
    pictures_explain_scale = models.TextField(verbose_name='宽与高的像素，两者用@分隔，每组用-分隔', default='', blank=True)
    content_table = models.CharField(max_length=1000, blank=True)
    answer_table = models.CharField(max_length=1000, blank=True)
    explain_table = models.CharField(max_length=1000, blank=True)
    online = models.BooleanField(default=False)
    download_total = models.PositiveIntegerField(verbose_name='下载次数', default=0)
    bank_point = models.PositiveIntegerField(verbose_name='库币', default=1)
    objects = models.Manager()
    IsOnline = OnlineManager()
    IsPublic = PublicManager()
    IsPublicAndOnline = PublicAndOnlineManager()
    favorite = models.ManyToManyField(to=User, related_name='FavoriteQuestion')
    wrong = models.ManyToManyField(to=User, through='WrongQuestion', through_fields=['question', 'user'],
                                   related_name='wrong')
    do_user = models.ManyToManyField(to=User, through='UserDoQuestionLog', through_fields=['question', 'user'],
                                     related_name='do_question')
    need_video = models.BooleanField(default=False, verbose_name='视频解析')
    expiration = models.DateTimeField(verbose_name='过期时间', default=timezone.now)
    permit_user = models.ManyToManyField(User, through='PermitVideoOfQuestion', through_fields=('question', 'user'),
                                         related_name='permit_question')

    class Meta:
        verbose_name = '题目'
        verbose_name_plural = verbose_name
        ordering = ['order', '-publish_time']

    def __str__(self):
        return str(self.id) + '-' + self.content[:20]


# 标签
class Tag(models.Model):
    name = models.CharField(max_length=100, verbose_name='名称', blank=False)
    owner = models.ForeignKey(User, verbose_name='拥有者', on_delete=models.CASCADE, related_name="tag")
    order = models.SmallIntegerField(verbose_name='次序', default=1)

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = verbose_name
        ordering = ['order']

    def __str__(self):
        return str(self.id) + '-' + self.name

    def save(self, *args, **kwargs):
        if not self.pk:  # 仅在新建对象时执行以下逻辑
            qs = self.__class__.objects.all().order_by('order')
            last_obj = qs.last()
            if last_obj:
                self.order = last_obj.order + 1
            else:
                self.order = 1
        super().save(*args, **kwargs)


class Question(models.Model):
    content = models.TextField(verbose_name='内容', blank=False)
    answer = models.TextField(verbose_name='正确答案', blank=False, default='略')
    explain = models.TextField(verbose_name='解析', blank=False, default='略')
    reference = models.CharField(max_length=100, verbose_name='引用哪里', blank=True, default='原创')
    type = models.SmallIntegerField(verbose_name='题型', choices=QUESTION_TYPE_CHOICES, default=1)
    difficulty_level = models.SmallIntegerField(verbose_name='难度', choices=DIFFICULTY_LEVEL_CHOICES, default=2)
    owner = models.ForeignKey(User, verbose_name='拥有者', on_delete=models.CASCADE, related_name="question")
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='录入时间')
    publish_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    last_edit_time = models.DateTimeField(auto_now_add=True, verbose_name='修改时间')
    open_level = models.CharField(verbose_name='开放程度', choices=OPEN_LEVEL_CHOICES, max_length=10,
                                  default=OPEN_LEVEL_CHOICES[0][0])
    top = models.BooleanField(default=False, verbose_name='置顶')
    # node = models.ForeignKey(to='Node', on_delete=models.CASCADE, verbose_name='节点', related_name="question")
    online = models.BooleanField(default=False)
    order = models.SmallIntegerField(verbose_name='题号', default=1)
    tag = models.ManyToManyField(Tag, through='Tag2Question', through_fields=('question', 'tag'))

    class Meta:
        verbose_name = '试题'
        verbose_name_plural = verbose_name
        ordering = ['order', '-publish_time']

    def __str__(self):
        return str(self.id) + '-' + self.content[:20]


# 章节节点
class Node(models.Model):
    """
    章节节点
    """
    CATEGORY_TYPE = (
        (1, '一级目录'),
        (2, '二级目录'),
        (3, '三级目录'),
        (4, '四级目录'),
    )
    name = models.CharField(max_length=30, verbose_name='节点名')
    parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE, blank=True, related_name='children')
    # order = models.SmallIntegerField(verbose_name='同个目录下的节点排序', default=1)
    order = OrderField(blank=True, for_fields=['parent'], verbose_name='排序序号')
    # category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name='类别描述')
    owner = models.ForeignKey(User, verbose_name='拥有者', on_delete=models.CASCADE, related_name="nodes")
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='录入时间')
    overview = models.CharField(max_length=200, verbose_name='简介', help_text='简介', blank=True, default='略')
    cover = models.TextField(default='/static/avatar/book.png', blank=True)
    question = models.ManyToManyField(to=Question, through='Node2Question',
                                      through_fields=('node', 'question'))
    teamworker = models.ManyToManyField(to=User, through='NodeCooperation', through_fields=('node', 'user'))

    class Meta:
        verbose_name = '节点'
        verbose_name_plural = verbose_name
        ordering = ['order']
        # ordering = ['parent', 'order']

    def __str__(self):
        return self.name


class Video(models.Model):
    # title = models.CharField(max_length=100, blank=False)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    price = models.PositiveIntegerField(default=1)
    url = models.TextField(verbose_name=u'网址', blank=False)
    qr_code = models.ImageField(upload_to='qrcode/%Y%m%d', verbose_name=u'二维码', blank=True, default='')
    question = models.ForeignKey(to=Questions, on_delete=models.CASCADE, verbose_name=u'试题', related_name='video')
    owner = models.ForeignKey(to=User, on_delete=models.CASCADE, verbose_name=u'录入者', related_name="videos")

    class Meta:
        verbose_name = '微视频'
        verbose_name_plural = verbose_name
        ordering = ['-add_time', 'owner']

    def __str__(self):
        return self.url[:30]


File_TYPE_CHOICES = (
    (1, '导学案'),
    (2, '课件')
)
PAPER_TYPE_CHOICES = (
    (1, '新课'),
    (2, '复习课')
)


class GuidePaper(models.Model):
    title = models.CharField(max_length=100, verbose_name='标题', blank=False)
    remark = models.CharField(max_length=1000, verbose_name='备注说明，比如适用年级，该导学/课件的优点等等', blank=True)
    owner = models.ForeignKey(User, verbose_name='录入者', on_delete=models.CASCADE, related_name="guide_papers")
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='录入时间')
    open_level = models.CharField(verbose_name='开放程度', choices=OPEN_LEVEL_CHOICES, max_length=10,
                                  default=OPEN_LEVEL_CHOICES[1][0])
    online = models.BooleanField(default=False)
    top = models.BooleanField(default=False, verbose_name='置顶')
    knowledgepoint = models.ForeignKey(to='KnowledgePoint', on_delete=models.CASCADE, verbose_name='知识点',
                                       related_name="guide_papers")
    order = OrderField(blank=True, for_fields=['knowledgepoint'], verbose_name='排序序号', default=0,
                       help_text="数字小的靠前")
    file = models.CharField(max_length=300, blank=False, verbose_name='导学案(课件)下载路径')
    type = models.SmallIntegerField(verbose_name='文件类型', choices=File_TYPE_CHOICES, default=1)
    reference = models.CharField(max_length=100, verbose_name='来源', blank=True)
    download_total = models.PositiveIntegerField(verbose_name='下载次数', default=0)
    bank_point = models.PositiveIntegerField(verbose_name='所需库币', default=5)
    paper_type = models.SmallIntegerField(verbose_name='课型', choices=PAPER_TYPE_CHOICES, default=1)

    class Meta:
        verbose_name = '学思案/课件'
        verbose_name_plural = verbose_name
        ordering = ['add_time']

    def __str__(self):
        return self.title


# 图片的插图，多对多模型
class ImageOfQuestion(models.Model):
    question = models.ForeignKey(Questions, verbose_name='题目', on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to='images/%Y%m%d/', verbose_name='题目路径')
    owner = models.ForeignKey(User, verbose_name='录入者', on_delete=models.CASCADE, related_name="images")
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

    class Meta:
        verbose_name = '插图'
        verbose_name_plural = verbose_name
        ordering = ['add_time']

    def __str__(self):
        return self.image


# 节点多对多试题
class Node2Question(models.Model):
    node = models.ForeignKey(Node, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    # owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        verbose_name = '知识点-题目'
        verbose_name_plural = verbose_name
        unique_together = (('node', 'question'),)

    def __str__(self):
        return self.node.name + self.question.content[:10]


# 知识点多对多试题
class KnowledgePoint2Question(models.Model):
    knowledgepoint = models.ForeignKey(KnowledgePoint, on_delete=models.CASCADE)
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    # owner = models.ForeignKey(User, on_delete=models.CASCADE)
    # owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='KnowledgePoint2Question')

    class Meta:
        verbose_name = '知识点-题目'
        verbose_name_plural = verbose_name
        unique_together = (('knowledgepoint', 'question'),)

    def __str__(self):
        return self.knowledgepoint.name + self.question.content[:10]


Grade_CHOICES = (
    (1, '高一'),
    (2, '高二'),
    (3, '高三'),
    (4, '高考'),
    (5, '学考'),
)


# 联考卷基础类
class Paper(models.Model):
    publish_time = models.DateTimeField(default=timezone.now)
    title = models.CharField(max_length=50, verbose_name='标题', help_text="大数据练习题/月考/")
    description = models.CharField(max_length=50, verbose_name='试卷描述', blank=True, help_text="比如专题练习python的函数")
    score = models.IntegerField(verbose_name='总分', default=50, help_text="总分")
    add_time = models.DateTimeField(default=timezone.now, verbose_name='录入时间')
    last_edit_time = models.DateTimeField(auto_now_add=True, verbose_name='修改时间')
    is_joint = models.BooleanField(default=False, verbose_name='是否为联考卷')
    open_level = models.CharField(verbose_name='开放程度', choices=OPEN_LEVEL_CHOICES, max_length=10,
                                  default=OPEN_LEVEL_CHOICES[0][0])
    online = models.BooleanField(default=False)
    top = models.BooleanField(default=False, verbose_name='置顶')
    owner = models.ForeignKey(User, verbose_name='录入者', on_delete=models.CASCADE, related_name="Paper")
    revisable = models.BooleanField(default=False, verbose_name='是否可修改')
    download_total = models.PositiveIntegerField(verbose_name='下载次数', default=0)
    file = models.TextField(blank=True, default='', verbose_name='试卷下载路径')
    file_explain = models.FileField(upload_to='examination/%Y%m%d', verbose_name='解析下载路径', blank=True, default='')
    grade = models.IntegerField(verbose_name='年级', choices=Grade_CHOICES, default=3)
    subject = models.ForeignKey(Subject, verbose_name='属于学科', on_delete=models.CASCADE, related_name="Paper", default=1)
    challenge = models.ManyToManyField(to=User, through='ChallengePaperOfUser', through_fields=['paper', 'user'],
                                       related_name='challenge')

    class Meta:
        abstract = True


# 联考卷，继承自基础类
class ExaminationPaper(Paper):
    questions = models.ManyToManyField(Questions, through='QuestionOfPaper', through_fields=('paper', 'question'))
    permit_user = models.ManyToManyField(User, through='PermitExplainPaperOfUser', through_fields=('paper', 'user'))
    expiration = models.DateTimeField(verbose_name='过期时间', default=timezone.now)
    bank_point = models.PositiveIntegerField(verbose_name='下载所需库币', default=2)

    class Meta:
        verbose_name = '测试卷'
        verbose_name_plural = verbose_name
        ordering = ['-publish_time', 'subject', '-grade']

    def __str__(self):
        return self.title


# 试卷多对多试卷
class QuestionOfPaper(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name="试题")
    paper = models.ForeignKey(ExaminationPaper, on_delete=models.CASCADE, verbose_name='试卷/练习')
    score = models.IntegerField(verbose_name="分值", default=2, help_text="每道题的分值")
    publish_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')

    class Meta:
        verbose_name = "单个题目"
        verbose_name_plural = verbose_name
        unique_together = [('question', 'paper')]  # 新增代码

    def __str__(self):
        return self.paper.title + self.question.content[:10]


class FeedbackBaseClass(models.Model):
    content = models.CharField(max_length=1000, verbose_name='反馈内容', blank=True)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='反馈时间')
    has_Read = models.BooleanField(default=False, verbose_name='是否已读')
    reply = models.TextField(blank=True, default='')

    def __str__(self):
        return self.content

    class Meta:
        abstract = True


class Feedback(FeedbackBaseClass):
    owner = models.ForeignKey(User, verbose_name='反馈者', on_delete=models.CASCADE, related_name="Feedback")

    class Meta:
        verbose_name = "反馈建议"
        verbose_name_plural = verbose_name


class QuestionFeedback(FeedbackBaseClass):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name="试题")
    owner = models.ForeignKey(User, verbose_name='反馈者', on_delete=models.CASCADE, related_name="FeedbackQuestion")

    class Meta:
        verbose_name = "反馈题目错误"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content


class GuidePaperFeedback(FeedbackBaseClass):
    paper = models.ForeignKey(GuidePaper, on_delete=models.CASCADE, verbose_name="导学案")
    owner = models.ForeignKey(User, verbose_name='反馈者', on_delete=models.CASCADE, related_name="FeedbackGuidePaper")

    class Meta:
        verbose_name = "反馈导学案错误"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content


APPLICATION_STATUS_CHOICE = (
    (0, "未处理"),
    (1, "同意"),
    (2, "拒绝"),
    (3, "再次申请，未处理")
)


# 申请单公共属性
class ApplicationBase(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    add_date = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    status = models.IntegerField(verbose_name='申请状态', choices=APPLICATION_STATUS_CHOICE, default=0)
    last_edit_time = models.DateTimeField(auto_now_add=True, verbose_name='修改时间')
    detail = models.CharField(max_length=200, verbose_name='详情内容', blank=True)

    class Meta:
        abstract = True


class GeneralPaperApplication(ApplicationBase):
    paper = models.ForeignKey(ExaminationPaper, on_delete=models.CASCADE, related_name='GeneralPaperApplication')

    class Meta:
        verbose_name = "非联考卷上线申请"
        verbose_name_plural = verbose_name
        ordering = ["-add_date", 'user']

    def __str__(self):
        return self.paper.title


class JointPaperApplication(ApplicationBase):
    paper = models.ForeignKey(ExaminationPaper, on_delete=models.CASCADE, related_name='JointPaperApplication')

    class Meta:
        verbose_name = "联考卷上线申请"
        verbose_name_plural = verbose_name
        ordering = ["-add_date", 'user']

    def __str__(self):
        return self.paper.title


class GuidePaperApplication(ApplicationBase):
    paper = models.ForeignKey(GuidePaper, on_delete=models.CASCADE, related_name='GuidePaperApplication')

    class Meta:
        verbose_name = "导学案上线申请"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.paper.title


class QuestionOnlineApplication(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    add_date = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, related_name='QuestionOnlineApplication')
    status = models.IntegerField(verbose_name='申请状态', choices=APPLICATION_STATUS_CHOICE, default=0)
    last_edit_time = models.DateTimeField(auto_now_add=True, verbose_name='修改时间')

    class Meta:
        verbose_name = "单题上线申请"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.question


class QuestionPrivateOnlineApplication(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    add_date = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='QuestionPrivateOnlineApplication')
    status = models.IntegerField(verbose_name='申请状态', choices=APPLICATION_STATUS_CHOICE, default=0)
    last_edit_time = models.DateTimeField(auto_now_add=True, verbose_name='修改时间')

    class Meta:
        verbose_name = "私人试题上线申请"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.question


class DownloadLog(models.Model):
    content_type = models.ForeignKey(ContentType,
                                     on_delete=models.CASCADE,
                                     related_name='download',
                                     limit_choices_to={'model__in': (
                                         'ExaminationPaper',
                                         'Questions',
                                         'GuidePaper'
                                     )})
    object_id = models.PositiveIntegerField()
    resource = GenericForeignKey('content_type', 'object_id')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='下载时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='下载者')


# 下载题目记录
class DownloadQuestionLog(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name='题目',
                                 related_name='DownloadQuestionLog')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='下载时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='下载者')


# 下载导学案记录
class DownloadGuidePaperLog(models.Model):
    guide_paper = models.ForeignKey(GuidePaper, on_delete=models.CASCADE, verbose_name='导学案',
                                    related_name='DownloadGuidePaperLog')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='下载时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='下载者')


# 下载试卷
class DownloadExaminationPaperLog(models.Model):
    examination_paper = models.ForeignKey(ExaminationPaper, on_delete=models.CASCADE, verbose_name='试卷',
                                          related_name='DownloadExaminationPaperLog')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='下载时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='下载者')


# 多对多中间表，做题刷题
class ChallengePaperOfUser(models.Model):
    question_amount = models.PositiveIntegerField(verbose_name='做题数量', default=12)
    accuracy = models.DecimalField(verbose_name='正确率', default=0, decimal_places=2, max_digits=10)
    score = models.PositiveIntegerField(verbose_name='得分', default=0)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='挑战者')
    paper = models.ForeignKey(ExaminationPaper, on_delete=models.CASCADE, verbose_name='试卷')


# 允许解析试卷的用户
class PermitExplainPaperOfUser(models.Model):
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='申请者')
    paper = models.ForeignKey(ExaminationPaper, on_delete=models.CASCADE, verbose_name='试卷')
    status = models.IntegerField(verbose_name='申请状态', choices=APPLICATION_STATUS_CHOICE, default=0)

    class Meta:
        verbose_name = "申请解析试卷用户"
        verbose_name_plural = verbose_name
        ordering = ["-add_time", 'status']

    def __str__(self):
        return self.user.username + self.paper.title + str(self.status)


# 标签tag与question多对多
class Tag2Question(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='试题')
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE, verbose_name='标签')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')


# 错题
class WrongQuestion(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name='题目')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='收藏者')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')


# 用户做题记录
class UserDoQuestionLog(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name='题目')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='收藏者')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')


# 用户做题记录
class UserPlayVideoLog(models.Model):
    video = models.ForeignKey(Video, on_delete=models.CASCADE, verbose_name='视频')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='观看者')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='时间')


SWIPER_TYPE_CHOICES = (
    ('guide', 'guide'),
    ('compose', 'compose'),
    ('exercise', 'exercise'),
    ('other', 'other')
)


# 小程序轮播图
class SwiperImage(models.Model):
    image_url = models.ImageField(upload_to='swiper/%Y%m%d', verbose_name='轮播图路径')
    href_url = models.TextField(default='', blank=True)
    type = models.TextField(verbose_name='类型', default='guide', blank=True, choices=SWIPER_TYPE_CHOICES)
    top = models.PositiveIntegerField(verbose_name='置顶位置', default=0)
    title = models.TextField(default='', blank=True)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

    class Meta:
        verbose_name = "轮播图"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


# 小程序公告栏
class Bulletin(models.Model):
    title = models.TextField(default='默认', blank=True, verbose_name='公告标题')
    content = models.TextField(default='空', blank=True, verbose_name='公告内容')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='公告添加时间')

    class Meta:
        verbose_name = "公告栏"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


# 小程序首页分类图标
class Category(models.Model):
    name = models.TextField(default='默认', blank=True, verbose_name='分类名称')
    icon = models.ImageField(upload_to='category/%Y%m%d', verbose_name='图标路径')
    href_url = models.TextField(default='', blank=True, verbose_name='路由')

    # add_time = models.DateTimeField(auto_now_add=True, verbose_name='分类添加时间')

    class Meta:
        verbose_name = "分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 教学辅导书籍
class Book(models.Model):
    name = models.TextField(default='默认', blank=True, verbose_name='书籍名称')
    remark = models.TextField(default='默认', blank=True, verbose_name='书籍简介')
    cover = models.ImageField(upload_to='book/%Y%m%d', verbose_name='图标路径')
    file = models.FileField(upload_to='book/%Y%m%d', verbose_name='文件路径')
    author = models.TextField(default='张三', blank=True, verbose_name='作者')
    publish_date = models.DateTimeField(auto_now_add=True, verbose_name='出版时间')

    class Meta:
        verbose_name = "教辅"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


# 允许解析试卷的用户
class PermitVideoOfQuestion(models.Model):
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='申请者')
    question = models.ForeignKey(Questions, on_delete=models.CASCADE, verbose_name='试题')
    status = models.PositiveIntegerField(verbose_name='申请状态', choices=APPLICATION_STATUS_CHOICE, default=0)

    class Meta:
        verbose_name = "申请上传试题视频"
        verbose_name_plural = verbose_name
        ordering = ["-add_time", 'status']

    def __str__(self):
        return self.user.username + self.question.content[:10] + str(self.status)


# 协作node的关系
class NodeCooperation(models.Model):
    node = models.ForeignKey(Node, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

    class Meta:
        verbose_name = '协作关系'
        verbose_name_plural = verbose_name
        unique_together = (('node', 'user'),)

    def __str__(self):
        return self.node.name + self.user.username


# 课堂作业
class Seatwork(models.Model):
    name = models.TextField(default='课堂作业', blank=True, verbose_name='名称')
    owner = models.ForeignKey(User, verbose_name='创建者', on_delete=models.CASCADE, related_name="seatworks")
    question = models.ManyToManyField('Questions', through='QuestionOfWork',
                                      through_fields=('seatwork', 'question'))


# 作业和试题多对多关系
class QuestionOfWork(models.Model):
    seatwork = models.ForeignKey(Seatwork, on_delete=models.CASCADE)
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

    class Meta:
        verbose_name = '作业和试题关系'
        verbose_name_plural = verbose_name
        unique_together = (('seatwork', 'question'),)
        ordering = ["-add_time"]

    def __str__(self):
        return self.seatwork.name + self.question.content[:10]


# 教师布置作业
class SetWork(models.Model):
    seatwork = models.ForeignKey(Seatwork, on_delete=models.CASCADE)
    teacher = models.ForeignKey(User, on_delete=models.CASCADE)
    open_answer = models.BooleanField(verbose_name='开放答案', default=True)
    permit_write = models.BooleanField(verbose_name='允许查看', default=True)
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    class_grade = models.ManyToManyField(ClassGrade, db_table='question_classwork',)

    class Meta:
        verbose_name = '教师布置作业'
        verbose_name_plural = verbose_name
        ordering = ["-add_time"]

    def __str__(self):
        return self.seatwork.name + self.teacher.username

#
# class ClassOfSetWork(models.Model):
#     setwork = models.ForeignKey(SetWork, on_delete=models.CASCADE)
#     class_grade = models.ForeignKey(ClassGrade, on_delete=models.CASCADE)
#     add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
#
#     class Meta:
#         verbose_name = '班级和布置作业关系'
#         verbose_name_plural = verbose_name
#         unique_together = (('setwork', 'class_grade'),)
#
#     def __str__(self):
#         return self.setwork.seatwork.name + self.class_grade.name


# 学生答题记录
class WorkRecord(models.Model):
    setwork = models.ForeignKey(SetWork, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='WorkRecord')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    score_rate = models.TextField(default='0%', blank=True, verbose_name='得分率')

    class Meta:
        verbose_name = '学生答题记录'
        verbose_name_plural = verbose_name
        ordering = ["-add_time"]

    def __str__(self):
        return self.setwork.seatwork.name + '答题结果'


# 学生答题记录子项
class WorkRecordItem(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    result = models.TextField(default='N', blank=True, verbose_name='答题结果')
    user_write = models.TextField(default='N', blank=True, verbose_name='学生自己答题')
    work_record = models.ForeignKey(WorkRecord, on_delete=models.CASCADE, related_name='WorkRecordItem')
    add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')

    class Meta:
        verbose_name = '答题记录子项'
        verbose_name_plural = verbose_name
        ordering = ["-add_time"]

    def __str__(self):
        return self.question.content[:15]
